﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Facebook.Service.Core;
using Facebook.Service;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace FriendsNearby.Services.Facebook
{
    public class FacebookServiceFactory : ISocialNetworkServiceFactory
    {
        FacebookService storedService = null;
        DataAccess da;

        public FacebookServiceFactory()
        {
            da = PolicyInjection.Create<DataAccess>();
        }

        #region IFacebookSessionFactory Members

        public FacebookService CreateInstanceForUser(string userId)
        {
            if (storedService != null && storedService.UserID == userId)
                return storedService;
            else
            {
                try
                {
                    string userSessionKey = da.GetUserSessionKey(userId);

                    FacebookService fs = new FacebookService(ConfigHelper.FacebookApplicationKey,
                                ConfigHelper.FacebookSecretKey,
                                userSessionKey,
                                userId);

                    Logger.Write(String.Format("Creating facebook service with ApplicationKey:{0} and SecretKey: {1} "
                                    + "for userId: {2} with SessionKey: {3}", ConfigHelper.FacebookApplicationKey,
                                    ConfigHelper.FacebookSecretKey, userId, userSessionKey));

                    // force request to check FacebookService connection
                    User myUser = fs.Users.GetUser(userId, "name");
                    if (myUser == null) {
                        LogEntry logEntry = new LogEntry();
                        logEntry.Message = String.Format(Properties.Resources.ErrorLog, userId);
                        logEntry.Categories.Add("Oddities");
                        logEntry.EventId = LogEventIds.UnableToEstablishSessionForUser;

                        Logger.Write(logEntry);
                        fs = null;
                    }

                    return fs;                    
       
                }
                catch (Exception ex)
                {
                    LogEntry logEntry = new LogEntry();
                    logEntry.Message = String.Concat(String.Format(Properties.Resources.ErrorLog, userId), "\nException:", ex.Message, "\nFull:", ex);
                    logEntry.Categories.Add("Oddities");
                    logEntry.EventId = LogEventIds.UnableToEstablishSessionForUserException;

                    Logger.Write(logEntry);
                    return null;
                }
            }
        }

        public void RegisterKnownSession(FacebookSession session)
        {
            storedService = new FacebookService(session);
        }

        #endregion
    }
}
